﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using System.Data;

using yncTech.BusinessObjects;
using yncTech.Common;
using yncTechWeb.Controls;
using EntitySpaces.Interfaces;

public partial class Admin_FinMov_FinMov005a : AdminBasePage
{
    DataTable StoreLocation = new DataTable();


    //        //SELECT a.ThirdUnitID,c.ThirdUnitNumberID,a.Name+'->'+b.Name+'->'+c.Name FROM dbo.BF_ThirdUnit AS a INNER JOIN BF_ThirdUnitCabin AS b ON a.ThirdUnitID = b.ThirdUnitID
    //INNER JOIN BF_ThirdUnitNumber AS c ON b.ThirdUnitCabinID = c.ThirdUnitCabinID
    //ORDER BY a.ThirdUnitID ,b.Name,c.Name

    decimal shipID = -1;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Request.QueryString[FinShippingMetadata.ColumnNames.ShipID] != null)
        {
            shipID = decimal.Parse(Request.QueryString[FinShippingMetadata.ColumnNames.ShipID]);
        }

        if (!IsPostBack)
        {
            FinShipping fs = new FinShipping();
            fs.LoadByPrimaryKey(shipID);

            BFThirdUnitQuery q1 = new BFThirdUnitQuery("q1");
            BFThirdUnitCabinQuery q2 = new BFThirdUnitCabinQuery("q2");
            BFThirdUnitNumberQuery q3 = new BFThirdUnitNumberQuery("q3");
            q1.InnerJoin(q2).On(q1.ThirdUnitID == q2.ThirdUnitID)
                .InnerJoin(q3).On(q2.ThirdUnitCabinID == q3.ThirdUnitCabinID);
            q1.Select(q3.ThirdUnitNumberID.As("Value"), (q1.Name + "->" + q2.Name + "->" + q3.Name).As("Text"));
            q1.Where(q1.ThirdUnitID == fs.ToDestination);
            q1.OrderBy(q1.ThirdUnitID.Ascending, q2.Name.Ascending, q3.Name.Ascending);
            StoreLocation = q1.LoadDataTable();
        }

    }

    protected void PageChanged(object sender, DataGridPageChangedEventArgs e)
    {
        if (IsPostBack)
        {
            return;
        }
        GridDataBind(e.NewPageIndex);
    }

    void GridDataBind(int page)
    {

        VBoxReceiptsQuery q1 = new VBoxReceiptsQuery();
        FinShippingBoxesQuery q2 = new FinShippingBoxesQuery();

        q1.SelectAll().Select(q2.ShippingBoxesID, q2.PackageNo);
        q1.InnerJoin(q2).On(q1.BoxID == q2.BoxID);
        q1.Where(q2.ShipID == shipID);

        pageGrid.DataSource = q1.LoadDataTable();
        pageGrid.CurrentPage = page;
        pageGrid.DataBind();
    }

    protected void On_ItemBound(object sender, RepeaterItemEventArgs e)
    {
        if (e.Item.ItemType.Equals(ListItemType.AlternatingItem)
           || e.Item.ItemType.Equals(ListItemType.Item))
        {
            DropDownList drpStore = e.Item.FindControl("drpStore") as DropDownList;

            drpStore.DataSource = StoreLocation;
            drpStore.DataValueField = "Value";
            drpStore.DataTextField = "Text";
            drpStore.DataBind();
        }
    }

    protected void btnSave_Click(object sender, EventArgs e)
    {
        try
        {
            lbMessage.Text = "";

            List<decimal> boxIDs = new List<decimal>();
            using (esTransactionScope tr = new esTransactionScope())
            {
                FinShipping fs = new FinShipping();
                fs.LoadByPrimaryKey(shipID);

                fs.ShippingStatus = ConstantValue.ShippingStatusCode.Confirmed;
                fs.UpdatedBy = fs.ReceivedBy = LoginUserInfo.CurrentUser.UserName;
                fs.UpdatedDttm = fs.ReceivedDttm = DateTime.Now;
                fs.Save();

                foreach (RepeaterItem item in pageGrid.Items)
                {

                    Label lbReceipt = (Label)item.FindControl("lbShipBoxID");
                    DropDownList drpStore = (DropDownList)item.FindControl("drpStore");

                    FinBoxReceiptsCollection boxRecs = new yncTech.BusinessObjects.FinBoxReceiptsCollection();
                    boxRecs.Query.Where(boxRecs.Query.BoxID == lbReceipt.Text);
                    boxRecs.Query.Load();

                    FinBox fb = new FinBox();

                    fb.LoadByPrimaryKey(decimal.Parse(lbReceipt.Text));

                    fb.StorageStatus = ConstantValue.StorageStatusCode.InStock;
                    fb.UpdatedBy = LoginUserInfo.CurrentUser.UserName;
                    fb.UpdatedDttm = DateTime.Now;
                    fb.Save();

                    FinReceiptCollection receipts = new yncTech.BusinessObjects.FinReceiptCollection();
                    receipts.Query.Where(receipts.Query.ReceiptID.In(boxRecs.Select(r => r.ReceiptID.Value).ToArray()));
                    receipts.Query.Load();
                    foreach (var rec in receipts)
                    {
                        rec.StorageStatus = ConstantValue.StorageStatusCode.InStock;
                        rec.ThirdUnitNumberId = new Guid(drpStore.SelectedValue);
                        rec.UpdatedBy = LoginUserInfo.CurrentUser.LoginName;
                        rec.UpdatedDttm = DateTime.Now;
                    }
                    receipts.Save();

                }

                List<string> listTo = new List<string>();
                List<string> listCC = new List<string>();

                string finMoveNo = fs.CreatedDttm.Value.ToString("yyMMdd") + fs.ShipID.ToString();

                string subject = string.Format(yncSettings.Mail.FinConfirm.MailSubject, finMoveNo);
                string content = yncSettings.Mail.FinConfirm.MailContent;

                string loginUrl = WebHelper.RootUrl() + "/Admin/AdminLogin.aspx";

                TSUserInfoCollection users = new TSUserInfoCollection();
                users.Query.Where(users.Query.ThirdUnitID == LoginUserInfo.CurrentUser.ThirdUnitID);
                users.Query.Load();

                BFThirdUnit btu = new BFThirdUnit();
                btu.LoadByPrimaryKey(fs.FromDestination.Value);


                BFThirdUnit btto = new BFThirdUnit();
                btu.LoadByPrimaryKey(fs.ToDestination.Value);

                TSUserInfo userInfo = new TSUserInfo();
                userInfo.Query.Where(userInfo.Query.UserName == (fs.CreatedBy));
                userInfo.Query.es.Top = 1;
                userInfo.Query.Load();

                
                if (fs.ShipManagerMail.Length > 0)
                {
                    listTo.Add(fs.ShipManagerMail);
                }
                if (userInfo.es.HasData)
                {
                    listTo.Add(userInfo.Email);
                }


                //Send mail to all user(same company)
                SendMail.SendHtml(listTo.ToArray(), subject, string.Format(content, finMoveNo, btu.Name, btto.Name, loginUrl));


                tr.Complete();

                WebHelper.CloseDialog(true);
            }

        }
        catch (Exception ex)
        {
            lbMessage.Text = ex.Message;
        }
    }



}